import { getWxSettings } from './settings'

const startMonitor = (listener: any)=> {

  wx.onLocationChange((result)=> {
    if (listener != null) {
      console.log("loc:", result.longitude, result.latitude)
      listener(result)
    }
  })
  
  console.log("start location monitor")
  wx.startLocationUpdateBackground({
    "type": "gcj02",
    success: ()=> {
      console.log("loc monitor success")
    },
    fail: (err)=> {
      console.log("monitor loc failed:", err.errMsg)
    }
  })
}

export const stopMonitor = () => {
  wx.stopLocationUpdate()
}

export const applyLocSvs = (listener: any, onFail = ()=>{}) => {
  if (!listener) {
    return
  }
  getWxSettings((list:any) => {
    console.log('检查位置权限')
    if (!list['scope.userLocationBackground']) {
      console.log('此用户未授权位置权限')
      onFail()
    } else {
      console.log('用户授权了位置权限, 向微信申请使用')
      wx.authorize({
        scope: 'scope.userLocationBackground',
        success: () => {
          startMonitor(listener)
        },
      fail: (err) => {
        console.log(err.errMsg)
        onFail()
      }
      })
    }
  })


  
}
